import { changeColor, genId } from "../utils/index";
export default function px2css({ main, position = "center" }) {
  const { pxMap, width, height } = main;
  let size = 1;
  let str = "";
  let left = 0,
    top = 0;
  let backgroundColor = "";
  const colors = [];
  if (position == "center") {
    left = ~~((width * size) / 2);
    top = ~~((height * size) / 2);
  }
  function getColor(color) {
    let index = colors.findIndex((c) => c.value == color);
    if (index != -1) {
      return `$color${index + 1}`;
    }
    let obj = {
      name: `$color${colors.length + 1}`,
      value: color,
    };
    colors.push(obj);
    return obj.name;
  }
  pxMap.forEach((point, index) => {
    let x = point.x - left;
    let y = point.y - top;
    let color = changeColor(point.color);
    let tab = index == pxMap.length - 1 ? ";" : ",";

    if (x == 0 && y == 0) {
      backgroundColor = getColor(color);
    }
    str += `${x}*$size ${y}*$size 0 ${getColor(color)}${tab}`;
  });
  let classContent = `$size:${size}px;${
    colors.map((c) => `\n${c.name}:${c.value}`).join(";") + ";"
  }
$ground:${str}
.px-${genId(2)}{
    width:$size;
    height:$size;
    background-color:${backgroundColor};
    box-shadow:$ground;
  }
  `;
  // console.log(colors);
  return classContent;
}
